<?php
/*
 * @FilePath: \crm\application\crm\controller\Login.php
 */
/*
 * @FilePath: \crm\application\crm\controller\Login.php
 */
/*
 * @FilePath: \crm\application\crm\controller\Login.php
 */
/*
 * @FilePath: \crm\application\crm\controller\Login.php
 */
/*
 * @FilePath: \crm\application\crm\controller\Login.php
 */

namespace app\crm\controller;

use app\crm\model\auth\Admin;
use app\crm\model\auth\YdCrmAdmin;
use think\captcha\Captcha;
use think\Controller;

class Login extends Controller
{
    /**
     * 初始化方法
     */
    public function initialize()
    {
        $action = $this->request->action();
        if (!empty(session('admin')) && !in_array($action, ['out'])) {
            $this->redirect('/crm/index/index');
        }
    }

    /**
     * 用户登录
     * @return string
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [
                'account|用户名'      => 'require',
                'password|密码'       => 'require',
                'captcha|验证码' => 'require|captcha',
            ];
            $result = $this->validate($post, $rule);

            $result !== true && $this->error($result);
            $msg = [
                'account'  => $post['account'],
                'password' => md5($post['password'])
            ];
            $admin = Admin::get($msg);
            empty($admin) && $this->error('用户名或密码错误');
            $admin['status'] == 1 && $this->error('账号已被禁用');

            unset($admin['password']);
            $admin['expire_time'] = time() + 7200;
            session('admin', $admin);
            $this->success('登录成功');
        }

        return $this->fetch();
    }

    /**
     * 用户退出
     * @return mixed
     */
    public function out()
    {
        session('admin', null);
        $this->success('退出登录成功', '/crm/login/index');
    }

    /** 
     * 验证码
    */
    public function captcha()
    {
        $captcha = new Captcha();
        $captcha->fontSize = 20;
        $captcha->length   = 4;
        return $captcha->entry();
    }
}
